<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="公告标题" prop="noticeTitle">
        <el-input
          v-model="queryParams.noticeTitle"
          :readonly="titleReadonly"
          placeholder="请输入公告标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:checktype:add']"
          v-if="checktypeList.length === 0"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:checktype:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="checktypeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="公告标题" align="center" prop="noticeTitle" />
       <!-- 新增部门名称列 -->
      <el-table-column label="部门" align="center">
          <template slot-scope="scope">
            {{ (scope.row.deptList && scope.row.deptList.map(item => item.deptName).join(', ')) || '-' }}
          </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:checktype:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:checktype:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="公告标题" prop="noticeTitle">
             <!--:disabled="true"新增禁用状态 -->
          <el-select 
            v-model="form.noticeId" 
            clearable 
            @visible-change="loadNoticeList" 
            @change="handleNoticeChange"
            :disabled="true"
          >
            <el-option
              v-for="item in sysNotices"
              :key="item.noticeId"
              :label="item.noticeTitle" 
              :value="item.noticeId"  
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="部门" prop="deptId">
          <el-checkbox v-model="deptExpand" @change="handleCheckedTreeExpand($event, 'dept')">展开/折叠</el-checkbox>
          <el-checkbox v-model="deptNodeAll" @change="handleCheckedTreeNodeAll($event, 'dept')">全选/全不选</el-checkbox>
          <el-checkbox v-model="form.deptCheckStrictly" @change="handleCheckedTreeConnect($event, 'dept')">父子联动</el-checkbox>
          <el-tree
            class="tree-border"
            :data="deptOptions"
            show-checkbox
            ref="dept"
            node-key="id"
            :check-strictly="!form.deptCheckStrictly"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSysNoticeDept, getSysNoticeDept, delSysNoticeDept, addSysNoticeDept, updateSysNoticeDept } from "@/api/system/sysNoticeDept";
import { listNotice } from "@/api/system/notice";
import { deptTreeselect } from '@/api/system/dept'

export default {
  name: "Checktype",
  data() {
    return {
      // 新增以下数据项
      deptExpand: true,
      deptNodeAll: false,
      defaultProps: {
        children: "children",
        label: "label"
      },
      deptOptions: [], // 部门树数据


      titleReadonly: false,
      sysNotices: [], // 存储公告列表数据
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 检查类型表格数据
      checktypeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        noticeTitle: '',
        id: null,
        typename: null,
        status: null,
        creater: null,
        createTime: null,
        operter: null,
        operTime: null,
      },
      
      // 表单参数
      form: {
        deptCheckStrictly: true, // 默认父子不联动
        deptId: '', // 存储字符串格式的部门ID（如 "1,2,3"）
        deptIds: [], // 存储数组格式的部门ID（如 [1, 2, 3]）
      },
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    const query = this.$route.query;
    if (query.noticeId) {
      this.defaultNoticeId = decodeURIComponent(query.noticeId);
      this.queryParams.noticeId = decodeURIComponent(query.noticeId);
      this.titleReadonly = query.readonly === 'true';
      this.handleQuery(); // 自动搜索
    }
    this.getList();
  },
  methods: {
  // 获取部门树数据
    getDeptTree() {
      return deptTreeselect({ parentid: 200,deptType:0 }).then(res => {
        this.deptOptions = this.normalizeDeptTree(res.data);
      });
    },
    
    // 规范化部门树结构
    normalizeDeptTree(depts) {
      return depts.map(item => ({
        id: item.deptId,
        label: item.deptName,
        children: item.children ? this.normalizeDeptTree(item.children) : []
      }));
    },
    
    // 获取所有选中的部门节点
    getDeptAllCheckedKeys() {
      let checkedKeys = this.$refs.dept.getCheckedKeys();
      let halfCheckedKeys = this.$refs.dept.getHalfCheckedKeys();
      return [...checkedKeys, ...halfCheckedKeys];
    },
    
    // 以下三个方法与之前角色管理中的相同
    handleCheckedTreeExpand(value, type) {
      if (type === 'dept') {
        this.deptOptions.forEach(item => {
          this.$refs.dept.store.nodesMap[item.id].expanded = value;
        });
      }
    },
    
    handleCheckedTreeNodeAll(value, type) {
      if (type === 'dept') {
        this.$refs.dept.setCheckedNodes(value ? this.deptOptions : []);
      }
    },
    
    handleCheckedTreeConnect(value, type) {
      if (type === 'dept') {
        this.form.deptCheckStrictly = !value;
      }
    },



    /** 查询检查类型列表 */
    getList() {
      this.loading = true;
      listSysNoticeDept(this.queryParams).then(response => {
        this.checktypeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 当下拉框展开时触发，加载公告列表
    async loadNoticeList(isOpen) {
      if (isOpen && this.sysNotices.length === 0) {
        try {
          const response = await listNotice(); // 调用接口
          this.sysNotices = response.rows || response.data; // 根据实际接口返回结构调整
        } catch (error) {
          console.error("加载公告列表失败:", error);
        }
      }
    },

    // 选中公告时的处理（可选）
    handleNoticeChange(noticeId) {
      // 如果需要根据选中ID做其他操作，例如更新其他字段
      console.log("选中的公告ID:", noticeId);
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        typename: null,
        status: null,
        creater: null,
        createTime: null,
        operter: null,
        operTime: null,
        delFlag: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
   /** 新增按钮操作 */
handleAdd() {
  this.reset();
  this.sysNotices = [];
  
  // 加载部门树
  this.getDeptTree().then(() => {
    this.loadNoticeList(true).then(() => {
      if (this.defaultNoticeId) {
        const matched = this.sysNotices.find(item => item.noticeId == this.defaultNoticeId);
        if (matched) {
          this.form.noticeId = matched.noticeId;
        } else {
          this.$modal.msgError("URL中指定的公告ID无效");
          return;
        }
      }
      this.open = true;
      this.title = "添加";
    });
  });
},

/** 修改按钮操作 */
handleUpdate(row) {
  this.reset();
  const id = row.id || this.ids;
  
  Promise.all([
    this.getDeptTree(),
    this.loadNoticeList(true),
    getSysNoticeDept(id)
  ]).then(([_, __, response]) => {
    this.form = response.data;
    
    // 将字符串格式的 deptId 转为数组（如 "1,2,3" => [1, 2, 3]）
    if (this.form.deptId) {
      this.form.deptIds = this.form.deptId.split(',').map(Number);
    } else {
      this.form.deptIds = [];
    }
    
    // 设置部门树的选中状态
    this.$nextTick(() => {
      this.$refs.dept.setCheckedKeys(this.form.deptIds);
    });
    
    if (this.sysNotices.some(item => item.noticeId === this.form.noticeId)) {
      this.open = true;
      this.title = "修改";
    } else {
      this.$modal.msgError("关联的公告不存在");
      this.open = false;
    }
  });
},
    /** 提交按钮 */
   /** 提交按钮 */
submitForm() {
  this.$refs["form"].validate(valid => {
    if (valid) {
      // 获取选中的部门ID（数组格式）
      const checkedDeptIds = this.getDeptAllCheckedKeys();
      
      // 将数组转为字符串（如 [1, 2, 3] => "1,2,3"）
      this.form.deptId = checkedDeptIds.join(',');
      
      if (this.form.id != null) {
        updateSysNoticeDept(this.form).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.getList();
        });
      } else {
        addSysNoticeDept(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      }
    }
  });
},
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除检查类型编号为"' + ids + '"的数据项？').then(function() {
        return delSysNoticeDept(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    
  }
};
</script>
